package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.his.po.Scheduling;               // 实体类
import com.neuedu.his.service.SchedulingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/** 医生排班计划 */
@RestController
@RequestMapping("/api/master/schedule")
public class ScheduleController {

    @Autowired
    private SchedulingService SchedulingService;

    // ===================== 分页查询 =====================
    @GetMapping
    public IPage<Scheduling> page(
            @RequestParam(defaultValue = "1") long page,
            @RequestParam(defaultValue = "10") long pageSize,
            @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate date,
            @RequestParam(required = false) Integer deptid,
            @RequestParam(required = false) Integer userid) {

        LambdaQueryWrapper<Scheduling> qw = new LambdaQueryWrapper<>();
        qw.eq(Scheduling::getDelmark, 1);

        if (date != null)  qw.eq(Scheduling::getScheddate, date);
        if (deptid != null) qw.eq(Scheduling::getDeptid, deptid);
        if (userid != null) qw.eq(Scheduling::getUserid, userid);

        qw.orderByAsc(Scheduling::getScheddate).orderByAsc(Scheduling::getNoon);

        return SchedulingService.page(new Page<>(page, pageSize), qw);
    }

    // ===================== 新增 / 修改 =====================
    @PostMapping
    public boolean create(@RequestBody Scheduling dto) {
        dto.setDelmark(1);
        return SchedulingService.save(dto);
    }

    @PutMapping("/{id}")
    public boolean update(@PathVariable Integer id, @RequestBody Scheduling dto) {
        dto.setId(id);
        return SchedulingService.updateById(dto);
    }

    // ===================== 逻辑删除 =====================
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        Scheduling tmp = new Scheduling();
        tmp.setId(id);
        tmp.setDelmark(0);
        return SchedulingService.updateById(tmp);
    }

    // ===================== 批量生成排班 =====================
    /** 
     * body: { "start":"2025-07-01", "end":"2025-07-31", "ruleIds":[1,2,3] }
     */
    @PostMapping("/generate")
    public boolean generate(@RequestBody GenReq req) {
        return SchedulingService.generateByRules(req);
    }

    /** 简单请求 DTO */
    public record GenReq(
            @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate start,
            @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate end,
            List<Integer> ruleIds) {}
}
